import { getTokenBySid } from '@/api/user/user';

import { isLogin } from '@/utils/user'
import { RouteLocationNormalized,RouteLocationNormalizedLoaded, NavigationGuardNext } from 'vue-router';
import * as cookie from '@/utils/cookie'
import { putConsole } from '@/api/console/console';
const SSO_URL = 'https://login.ops.qihoo.net:4436/sec/login';


const urlOrigin = window.location.origin;
// 登录用户默认跳转页面
const loginedUserHome = '/';

function getReferPath(): string {
    const refer = document.referrer || '';
    const { origin, pathname } = new URL(refer);
    if (origin === urlOrigin) {
        return pathname || '';
    }
    return '';
}

/** 登录 */
export const login = async (to:RouteLocationNormalized, from:RouteLocationNormalizedLoaded,next:NavigationGuardNext): Promise<void> => {
    
    let jump = to.query.jump as string;
    
    const rFrom: string = from.fullPath;
    jump = jump // 先从参数指定的jump地址获取
        || rFrom // 再从来源路由获取
        || getReferPath(); // 再从referrer获取
    if (isLogin()) {
        /** 防止循环重定向 */
        if (/^\/login/.test(jump)) {
            jump = loginedUserHome;
        }
        window.location.href = urlOrigin + jump;
    }
    const ref: string = urlOrigin + `/login-cb?jump=${jump}`;
    
    const loginURL: string = SSO_URL + '?ref=' + encodeURIComponent(ref);

    window.location.href = loginURL
    next()
}

/** 登录之后处理 */
export const logincb = async (to:RouteLocationNormalized, from:RouteLocationNormalizedLoaded): Promise<void> => {
    let jump = to.query.jump as string 
    const sid = to.query.sid;
    const rFrom: string = from.fullPath;
  
    jump = jump || rFrom || getReferPath();
    if (jump === '/' || /^\/login/.test(jump)) {
        jump = loginedUserHome;
    }

    if (isLogin()) {
        /** 已登录用户直接跳转路由 */
        window.location.href = urlOrigin + jump;
    }
    
    if (/^\w{32}$/.test(sid as string)) {
        
        /** 登录完成，调用后端接口换取token */
        const ref = urlOrigin + `/login-cb?jump=${jump}`;
        try {
             const { token, expireAt } = await getTokenBySid(sid as string, ref);
             cookie.set("u_login_token", token, {expires:expireAt - Date.now()});
             putConsole();
            setTimeout(() => {
                window.location.href = urlOrigin + jump;
            }, 200);
            return;
        } catch (e) {
            console.log('login fail:', e);
        }
    }
    /** 未登录或登录出错用户跳转至首页 */
    window.location.href = urlOrigin
}